package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qk.common.PageResult;
import com.qk.common.constant.BusinessStatusConstants;
import com.qk.common.constant.ClueStatusConstants;
import com.qk.common.constant.ClueTrackRecordType;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.common.util.CurrentUserContextHolders;
import com.qk.entity.domain.clue.ClueDO;
import com.qk.entity.domain.user.UserDO;
import com.qk.entity.Business;
import com.qk.entity.Clue;
import com.qk.entity.ClueTrackRecord;
import com.qk.entity.dto.clue.ClueDTO;
import com.qk.entity.dto.clue.ClueListDTO;
import com.qk.entity.dto.clue.CluePoolDTO;
import com.qk.entity.dto.clue.UpdateClueInfoDTO;
import com.qk.entity.vo.clue.CluePoolVO;
import com.qk.entity.vo.clue.ClueVO;
import com.qk.management.mapper.BusinessMapper;
import com.qk.management.mapper.ClueMapper;
import com.qk.management.mapper.ClueTrackRecordMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.ClueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author fantuan
 * @created 2025/10/13 17:04
 * @description
 */
@Service
public class ClueServiceImpl extends ServiceImpl<ClueMapper,Clue> implements ClueService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ClueTrackRecordMapper clueTrackRecordMapper;
    @Autowired
    private BusinessMapper businessMapper;
    @Override
    public ClueVO getClueInfoById(Integer id) {
        Clue clue = this.baseMapper.selectById(id);
        Integer userId = clue.getUserId();
        UserDO user = userMapper.getUserById(userId);
        List<ClueTrackRecord> clueTrackRecords = clueTrackRecordMapper.selectList(Wrappers.lambdaQuery(ClueTrackRecord.class)
                .in(ClueTrackRecord::getClueId,id));

        ClueVO clueVO = BeanUtil.copyProperties(clue, ClueVO.class);
        List<ClueVO.ClueTrackRecordVO> list = clueTrackRecords.stream().map(item -> {
            ClueVO.ClueTrackRecordVO vo = BeanUtil.copyProperties(item, ClueVO.ClueTrackRecordVO.class);
            vo.setAssignName(user.getName());
            return vo;
        }).toList();
        clueVO.setTrackRecords(list);
        return clueVO;

    }

    //@Transactional(rollbackFor = Exception.class)
    @Transactional
    @Override
    public void updateClueInfoById(UpdateClueInfoDTO dto) {
        Clue clue = BeanUtil.copyProperties(dto, Clue.class);
        clue.setUpdateTime(LocalDateTime.now());
        clue.setStatus(ClueStatusConstants.FOLLOW_UP);
        this.baseMapper.updateById(clue);
        ClueTrackRecord clueTrackRecord = BeanUtil.copyProperties(dto, ClueTrackRecord.class);
        clueTrackRecord.setCreateTime(LocalDateTime.now());
        clueTrackRecord.setId(null);
        clueTrackRecord.setClueId(clue.getId());
        clueTrackRecord.setType(ClueTrackRecordType.NORMAL);
        clueTrackRecord.setUserId(CurrentUserContextHolders.get());
        clueTrackRecordMapper.insert(clueTrackRecord);
    }

    @Transactional
    @Override
    public void toBusiness(Integer id) {
        Clue clue = this.baseMapper.selectById(id);
        clue.setStatus(ClueStatusConstants.CONVENT_TO_BUSINESS);
        clue.setUpdateTime(LocalDateTime.now());
        this.baseMapper.updateById(clue);
        Business business = BeanUtil.copyProperties(clue, Business.class);
        business.setId(null);
        business.setCreateTime(LocalDateTime.now());
        business.setUpdateTime(LocalDateTime.now());
        business.setUserId(null);
        business.setStatus(BusinessStatusConstants.WAIT_ALLOCATION);
        business.setClueId(id);
        this.businessMapper.insert(business);
    }

    @Override
    public PageResult<CluePoolVO> selectCluePool(CluePoolDTO dto) {
        Page pages = new Page<>(dto.getPage(),dto.getPageSize());
        Page<CluePoolVO> cluePoolVOPage = this.baseMapper.selectCluePool(pages,dto);
        return PageResult.<CluePoolVO>builder()
                .total(Long.valueOf(cluePoolVOPage.getTotal()).intValue())
                .rows(cluePoolVOPage.getRecords())
                .build();
    }


    private PageResult<ClueDO> clueListMp(ClueListDTO dto){
        Page pages = new Page<>(dto.getPage(),dto.getPageSize());
        Page<ClueDO> clueDOPage = this.baseMapper.selectByPageMp(pages,dto);
        return PageResult.<ClueDO>builder()
                .total(Long.valueOf(clueDOPage.getTotal()).intValue())
                .rows(clueDOPage.getRecords())
                .build();
    }
    @Override
    public PageResult<ClueDO> clueList(ClueListDTO dto) {
//        PageHelper.startPage(dto.getPage(),dto.getPageSize());
//        List<ClueDO> list = this.baseMapper.selectByPage(dto);
//        Page<ClueDO> page = (Page<ClueDO>) list;
//        return PageResult.<ClueDO>builder()
//                .total((int) page.getTotal())
//                .rows(page.getResult())
//                .build();
        return this.clueListMp(dto);
    }


    @Override
    public void addClue(ClueDTO dto) {

        if(ObjectUtil.isEmpty(dto.getPhone())||(ObjectUtil.isEmpty(dto.getChannel()))){
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        Clue clue = BeanUtil.copyProperties(dto, Clue.class);
        clue.setStatus(ClueStatusConstants.WAIT_ALLOCATION);
        clue.setCreateTime(LocalDateTime.now());
        clue.setUpdateTime(LocalDateTime.now());
        //this.baseMapper.insert(clue);
        this.save(clue);
    }


}
